<template>
  <div class="LoginBox">
    <transition>
      <div class="FaceIdentityLoginBox" v-show="showLeft">
        <div id="media" class="media">
          <video id="video" class="videoWindow" autoplay></video>
          <a class="FaceIdentityStatusText" >{{FaceIdentityStatus}}</a>
          <canvas id="canvas" class="canvas"></canvas>
        </div>
      </div>
    </transition>
    <div class="ClassicLoginBox">
      <el-text class="title">登 录 可 乎</el-text>
      <el-form :model="LoginUser" :rules="rules" status-icon ref="ruleForm" class="form">
        <el-form-item prop="username" class="formItem">
          <el-input
              v-model="LoginUser.username"
              placeholder="请输入用户名"
              size="large"
              maxlength="16"
              :prefix-icon="User"
              class="Input"/>
        </el-form-item>
        <el-form-item prop="password" class="formItem">
          <el-input
              v-model="LoginUser.password"
              placeholder="请输入密码"
              size="large"
              maxlength="18"
              :prefix-icon="Lock"
              show-password
              class="Input"/>
        </el-form-item>
      </el-form>
        <div class="buttonBox">
          <el-button type="primary" class="IdentityFaceLoginButton" round @click="OpenLeftWindow" >{{showLeft?"收起窗口":"刷脸登录"}}</el-button>
          <el-button type="primary" class="LoginButton" round @click="login">登录</el-button>
        </div>
    </div>
  </div>
</template>

<script>
import { User,Search,Lock,DArrowLeft } from "@element-plus/icons-vue";
import $ from 'jquery'
export default {
  name: "Login",
  inject: ['reload'],
  setup(){
    return {
      User,
      Search,
      Lock,
      DArrowLeft
    }
  },
  data() {
    // 用户名的校验方法
    let validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入用户名"));
      }
      return callback();
    };
    // 密码的校验方法
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入密码"));
      }
      // 长度在6-18之间,允许字母数字和下划线
      const passwordRule = /^\w{6,18}$/;
      if (passwordRule.test(value)) {
        return callback();
      } else {
        return callback(
            new Error("长度6-18之间,允许字母数字和下划线")
        );
      }
    };
    return {
      LoginUser: {
        username:"",
        password:""
      },
      showLeft:false,
      TimeInterval:undefined,
      video: undefined,
      canvas: undefined,
      context: undefined,
      FaceIdentityStatus: "正在识别....",
      user: {},
      rules: {
        username: [{ validator: validateName, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }]
      }
    }
  },
  methods: {
    OpenLeftWindow(){
      if(!this.showLeft){
        this.showLeft=true
        let video = document.getElementById("video") //获取video标签
        this.video = video
        this.canvas = document.getElementById("canvas")
        this.context = this.canvas.getContext("2d")
        let con ={
          audio:false,
          video:{
            width:1980,
            height:1024,
          }
        }
        navigator.mediaDevices.getUserMedia(con)
            .then(function (stream){
              video.srcObject=stream;
              video.onloadedmetadata = function(e){
                video.play();
              }
            })
        this.TimeInterval=window.setInterval(this.query,3000)
      }else{
        if(this.TimeInterval!=undefined||this.TimeInterval!=null){
          clearInterval(this.TimeInterval)
        }
        this.showLeft=false
      }
    },
    query(){
      this.context.drawImage(this.video,0,0,320,180);
      let base = this.getBase64();
      $.ajax({
        type:"post",
        url:"http://localhost:8080/faceLogin",
        data:{"base":base},
        dataType: "json",
        success:(res)=>{
          if(res.error_msg=="SUCCESS"){
            let user = res.result.user_list[0]
            let score = user.score
            let user_id = user.user_id
            if(score>80){
              this.FaceIdentityStatus="正在登录...."
              setTimeout(()=>{
                if(score>80){
                  clearInterval(this.TimeInterval)
                  this.$axios
                      .get(`${this.$target}/user/`+user_id+`/face`)
                      .then(res=>{
                        localStorage.setItem("user",JSON.stringify(res.data.data.User))
                        localStorage.setItem("userID",res.data.data.User.id)
                        localStorage.setItem("token",res.data.data.token)
                        this.notifySucceed("登录成功!")
                        this.$router.push({path:"/mainPage"})
                        this.reload()
                      })
                }else{
                  this.FaceIdentityStatus="重新扫描...."
                }
              },600)
            }
          }
        }
      });
    },
    getBase64() {
      let imgSrc = document.getElementById("canvas").toDataURL(
          "image/png",1);
      return imgSrc.split("base64,")[1];
    },
    login(){
      this.$refs["ruleForm"].validate(valid=>{
        if(valid){
          this.$axios
              .get(`${this.$target}/user?username=`+this.LoginUser.username+`&password=`+this.LoginUser.password)
              .then(res=>{
                if(res.data.status==0){
                  localStorage.setItem("user",JSON.stringify(res.data.data.User))
                  localStorage.setItem("userID",res.data.data.User.id)
                  localStorage.setItem("token",res.data.data.token)
                  this.notifySucceed("登录成功!")
                  this.$router.push({path:"/mainPage"})
                  this.reload()
                }else{
                  this.notifyError(res.data.message)
                }
              })
        }else{
          return false
        }
      })
    },
    goRegister(){
      this.$emit("GoRegister")
    }
  }
}
</script>

<style src="@/assets/less/Login.less" scoped lang="less"></style>